package cn.gailvlun.gll.presentation.emotion

import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.support.annotation.NonNull
import android.support.v4.app.ActivityOptionsCompat
import android.support.v7.widget.LinearLayoutManager
import android.text.Html
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import cn.gailvlun.gll.R
import cn.gailvlun.gll.bean.PlaceHolder
import cn.gailvlun.gll.databinding.ActivityEmotionDetail2Binding
import cn.gailvlun.gll.databinding.ItemEmotionDetail2EmotionBinding
import cn.gailvlun.gll.databinding.ItemEmotionLikeIconBinding
import cn.gailvlun.gll.net.HttpMethods
import cn.gailvlun.gll.net.HttpSubscriber
import cn.gailvlun.gll.net.ListRes
import cn.gailvlun.gll.net.base.Profile
import cn.gailvlun.gll.net.emotion.Comment
import cn.gailvlun.gll.net.emotion.CommentReplyReq
import cn.gailvlun.gll.net.emotion.Emotion
import cn.gailvlun.gll.presentation.base.BaseActivity
import cn.gailvlun.gll.presentation.emotion.bean.EmotionDetail
import cn.gailvlun.gll.presentation.emotion.bean.EmotionDetailTransfer
import cn.gailvlun.gll.presentation.emotion.core.BaseAdapter
import cn.gailvlun.gll.presentation.emotion.drawer.EmotionDetail2Adapter
import cn.gailvlun.gll.presentation.emotion.drawer.EmotionDetail2ViewModel
import cn.gailvlun.gll.presentation.emotion.photo.GalleryActivity
import cn.gailvlun.gll.presentation.emotion.photo.VIEW_NAME_IMAGE
import cn.gailvlun.gll.util.DialogUtil
import cn.gailvlun.gll.util.IsEmpty
import cn.gailvlun.gll.util.RxUtil
import cn.gailvlun.gll.util.ToastUtil
import com.blankj.utilcode.util.KeyboardUtils
import com.github.markzhai.recyclerview.BR
import com.github.markzhai.recyclerview.BaseViewAdapter
import com.jakewharton.rxbinding2.widget.RxTextView
import io.reactivex.functions.Consumer
import rx_activity_result2.Result
import rx_activity_result2.RxActivityResult


class EmotionDetail2Activity : BaseActivity() {
    private lateinit var mBinding: ActivityEmotionDetail2Binding
    private lateinit var mAdapter: BaseAdapter<Any>
    private lateinit var emotionDetail: EmotionDetail
    private lateinit var mViewModel: EmotionDetail2ViewModel
    private lateinit var mLikeListAdapter: EmotionLikeListAdapter
    private val replyCache: MutableMap<Int, String> = HashMap()
    private val commentReq = CommentReplyReq()
    private var mEmotion: Emotion? = null

    companion object {
        @JvmStatic
        fun openActivity(activity: BaseActivity, @NonNull transfer: EmotionDetailTransfer, consumer: Consumer<Result<BaseActivity>>) {
            val intent = Intent(activity, EmotionDetail2Activity::class.java)
            intent.putExtra("data", transfer)
            RxActivityResult.on(activity)
                    .startIntent(intent)
                    .subscribe(consumer)
        }

        @JvmStatic
        fun openActivity(activity: BaseActivity, @NonNull transfer: EmotionDetailTransfer) {
            val intent = Intent(activity, EmotionDetail2Activity::class.java)
            intent.putExtra("data", transfer)
            activity.startActivity(intent)
        }

        @JvmStatic
        fun openFromNotification(context: Context, transfer: EmotionDetailTransfer) {
            val i = Intent(context, EmotionDetail2Activity::class.java)
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            i.putExtra("data", transfer)
            context.startActivity(i)
        }

    }

    override fun initComponent() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_emotion_detail2)
        mAdapter = EmotionDetail2Adapter(mContext)
        mLikeListAdapter = EmotionLikeListAdapter()
        mViewModel = EmotionDetail2ViewModel(mContext, mAdapter)
        val presenter = Presenter()
        mBinding.presenter = presenter
        mBinding.vm = mViewModel
        mAdapter.setPresenter(presenter)
        mAdapter.setDecorator { holder, position, _ ->

            
            holder.binding.setVariable(BR.vm, mViewModel)
            holder.binding.executePendingBindings()
            val itemBinding = holder.binding

            
            if (itemBinding is ItemEmotionDetail2EmotionBinding) {
                itemBinding.llTextAndImage?.ctvContent?.isAvailableCollapse = false
                itemBinding.llTextAndImage?.igvEmotionImage?.setOnPhotoClickListener { iv, photos, position ->
                    val options = ActivityOptionsCompat.makeSceneTransitionAnimation(mContext, itemBinding.llTextAndImage.igvEmotionImage, VIEW_NAME_IMAGE + "-" + position)
                    GalleryActivity.openActivity(mContext, java.util.ArrayList(photos), position, null)
                }
                val emotion = mAdapter.getData()[position] as Emotion
                (itemBinding).rlToolBar?.ctvFunction?.setOnClickListener { view -> mViewModel.showFunction(view, emotion) }
            }
            





        }
        mBinding.rvEmotionList.adapter = mAdapter
        mBinding.rvEmotionList.layoutManager = LinearLayoutManager(mContext)

    }

    override fun createHandler() {
        mBinding.nbv.setOnBackListener {
            KeyboardUtils.hideSoftInput(mContext)
            onBackPressed() }





        mBinding.nbv.setOnMenuClickListener { view ->
            if (mEmotion != null) {
                mViewModel.showOperateEmotionWindow(view, mEmotion!!)
            }
        }

        RxTextView.textChanges(mBinding.etReply)
                .subscribe {
                    saveReply(it.toString())
                    if (it.isNotEmpty()) {
                        mViewModel.isSendObservable.set(true)
                    } else {
                        mViewModel.isSendObservable.set(false)
                    }
                }

        mBinding.etReply.setOnClickListener {
            if (!mBinding.etReply.isFocused) {
                emotionDetail.req.reply_id = null

                mBinding.etReply.isFocusable = true
                mBinding.etReply.isFocusableInTouchMode = true
                KeyboardUtils.showSoftInput(mBinding.etReply)
            }
        }


        KeyboardUtils.registerSoftInputChangedListener(this) {
            if (!KeyboardUtils.isSoftInputVisible(mContext)) {
                
                mBinding.etReply.tag = null
                mBinding.etReply.text = null
                mBinding.etReply.setHint("留言")
                mBinding.etReply.isFocusable = false
                mBinding.etReply.isFocusableInTouchMode = false
            }
        }
    }

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        return if (mViewModel.functionPopupWindow != null && mViewModel.functionPopupWindow!!.isShowing) {
            mViewModel.functionPopupWindow!!.dismiss()
            true
        } else {
            super.dispatchTouchEvent(ev)
        }
    }


    override fun loadData(savedInstanceState: Bundle?) {
        val data = intent.getSerializableExtra("data") as EmotionDetailTransfer
        emotionDetail = EmotionDetail(data)
        getData()
    }

    private fun getData() {

        var pd = DialogUtil.showIndeterminate(mContext)
        HttpMethods.getEmotionService()
                .emotionDetail(emotionDetail.transfer.id)
                .compose(RxUtil.applyScheduler())
                .compose(bindToLifecycle())
                .subscribe(object : HttpSubscriber<Emotion>() {
                    override fun onSuccess(response: Emotion?) {
                        pd.dismiss()
                        mBinding.invalidateAll()
                        mAdapter.clear()
                        if (response == null) {
                            mAdapter.add(null, EmotionDetail2Adapter.Type.EMPTY.ordinal)
                        } else {
                            emotionDetail.emotion = response
                            mEmotion = response
                            mAdapter.add(response, EmotionDetail2Adapter.Type.CONTENT.ordinal)

                        }

                        getComment()
                    }

                    override fun onFailure(errMsg: String?, response: Emotion?, code: Int) {
                        pd.dismiss()
                        DialogUtil.showError(mContext, errMsg)
                    }
                })
    }

    private fun getLikeList() {
        HttpMethods.getEmotionService()
                .likeList(emotionDetail.transfer.id)
                .compose(RxUtil.applyScheduler())
                .compose(bindToLifecycle())
                .subscribe(object : HttpSubscriber<MutableList<Profile>>() {
                    override fun onSuccess(response: MutableList<Profile>?) {
                        mLikeListAdapter.addAll(response)
                        mAdapter.notifyItemChanged(1)

                    }

                    override fun onFailure(errMsg: String?, response: MutableList<Profile>?, code: Int) {
                        DialogUtil.showError(mContext, errMsg)

                    }

                })
    }

    private fun getComment() {
        HttpMethods.getEmotionService()
                .commentList(emotionDetail.transfer.id,
                        emotionDetail.queryParam.lastId,
                        emotionDetail.queryParam.direction,
                        emotionDetail.order.desc)
                .compose(RxUtil.applyScheduler())
                .subscribe(object : HttpSubscriber<ListRes<Comment>>() {
                    override fun onSuccess(response: ListRes<Comment>) {
                        mAdapter.add("留言板", EmotionDetail2Adapter.Type.COMMENT_HEADER.ordinal)
                        if (response.results.size > 0) {
                            mViewModel.isCommentHeaderVisibleObservable.set(true)
                            mAdapter.addAll(response.results, EmotionDetail2Adapter.Type.COMMENT.ordinal)

                        } else {
                            mViewModel.isCommentHeaderVisibleObservable.set(false)
                        }
                    }

                    override fun onFailure(errMsg: String, response: ListRes<Comment>?, code: Int) {
                        DialogUtil.showError(mContext, errMsg)

                    }

                })
    }

    inner class EmotionLikeListAdapter : android.widget.BaseAdapter() {
        override fun getItem(p0: Int): Profile {
            return mList!![p0]
        }

        override fun getItemId(p0: Int): Long {
            return 0
        }

        private var mList: MutableList<Profile>? = ArrayList()
        private lateinit var mBinding: ItemEmotionLikeIconBinding

        fun addAll(list: MutableList<Profile>?) {
            mList = list
            notifyDataSetChanged()

        }

        override fun getCount(): Int {
            return mList?.size!!
        }

        override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {

            mBinding = DataBindingUtil.inflate(LayoutInflater.from(mContext), R.layout.item_emotion_like_icon, parent, false)

            mBinding.profile = getItem(position)

            return mBinding.root
        }

    }

    private fun restoreReplyContent(key: Int) {
        val reply = replyCache[key]
        mBinding.etReply.isFocusable = true
        mBinding.etReply.isFocusableInTouchMode = true
        mBinding.etReply.tag = key
        if (TextUtils.isEmpty(reply)) {
            mBinding.etReply.text = null
        } else {
            mBinding.etReply.setText(reply)
            mBinding.etReply.setSelection(reply!!.length)
        }
        KeyboardUtils.showSoftInput(mBinding.etReply)
    }

    private fun saveReply(reply: String) {
        if (mBinding.etReply.tag != null) {
            replyCache.put(mBinding.etReply.tag as Int, reply)
        }
    }


    inner class Presenter : BaseViewAdapter.Presenter {
        var pd: Dialog? = null
        fun onAddComment() {

            if (IsEmpty.string(mBinding.etReply.text.toString().trim())) {
                ToastUtil.showShort("请填写内容")
                return
            }
            pd = DialogUtil.showIndeterminate(mContext)
            if (KeyboardUtils.isSoftInputVisible(mContext)) {

                KeyboardUtils.hideSoftInput(mBinding.etReply)
            }
            val text = mBinding.etReply.text.toString()
            commentReq.setText(text)
            commentReq.record_id = emotionDetail.emotion.id

            HttpMethods.getEmotionService().commentReply(commentReq)
                    .compose(RxUtil.applyScheduler())
                    .compose<Comment>(bindToLifecycle<Comment>())
                    .subscribe(object : HttpSubscriber<Comment>() {
                        override fun onSuccess(response: Comment) {
                            pd?.dismiss()

                            emotionDetail.emotion.comment_num = emotionDetail.emotion.comment_num + 1
                            val mAdapter = mAdapter as EmotionDetail2Adapter
                            val position = mAdapter.findFirstPositionByViewType(EmotionDetail2Adapter.Type.COMMENT)
                            if (position == -1) {
                                mAdapter.add(response, EmotionDetail2Adapter.Type.COMMENT.ordinal)
                                mAdapter.removeByViewType(EmotionDetail2Adapter.Type.EMPTY)
                            } else {
                                mAdapter.add(position, response, EmotionDetail2Adapter.Type.COMMENT.ordinal)
                            }
                            mViewModel.isCommentHeaderVisibleObservable.set(true)
                            mAdapter.notifyDataSetChanged()
                            mBinding.etReply.text = null
                            commentReq.reply_id = null
                            commentReq.text = null
                            mBinding.etReply.setHint("留言")

                        }

                        override fun onFailure(errMsg: String, response: Comment?, code: Int) {

                            pd?.dismiss()
                            ToastUtil.showShort("留言失败")
                        }

                        override fun onComplete() {
                            super.onComplete()
                            pd?.dismiss()
                        }
                    })
        }


        fun onDeleteComment(comment: Comment) {
            HttpMethods.getEmotionService()
                    .deleteComment(comment.id)
                    .compose(RxUtil.applyScheduler())
                    .subscribe(object : HttpSubscriber<PlaceHolder>() {
                        override fun onSuccess(response: PlaceHolder) {
                            val mAdapter = mAdapter as EmotionDetail2Adapter
                            mAdapter.removeComment(comment)
                            if (mAdapter.getData().size > 2) {
                                mViewModel.isCommentHeaderVisibleObservable.set(true)
                            } else {
                                mViewModel.isCommentHeaderVisibleObservable.set(false)
                            }
                        }

                        override fun onFailure(errMsg: String, response: PlaceHolder?, code: Int) {
                            DialogUtil.showError(mContext, errMsg)
                        }
                    })
        }


        fun replyTo(c: Comment) {
            val text = getString(R.string.emotion_comment_hint_mode, c.owner.name)
            mBinding.etReply.hint = Html.fromHtml(text)
            commentReq.reply_id = c.owner.id

            mBinding.etReply.isFocusable = true
            mBinding.etReply.isFocusableInTouchMode = true
            KeyboardUtils.showSoftInput(mBinding.etReply)
        }

    }

    override fun onPause() {
        super.onPause()
        if (KeyboardUtils.isSoftInputVisible(mContext)) KeyboardUtils.hideSoftInput(mBinding.etReply)
    }



}